package com.hmp.recruit.sys.user.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hmp.recruit.sys.user.service.UserService;
import com.hmp.recruit.sys.user.service.impl.UserServiceImpl;
import com.hmp.recruit.sys.user.vo.SysUser;

@WebServlet("/sys/user")
public class UserController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private UserService userService = new UserServiceImpl();

    public UserController() {
    }

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//解决中文乱码
		resp.setContentType("text/html;charset=utf-8");
		//请求解决乱码
		req.setCharacterEncoding("utf-8");
		//响应解决乱码
		resp.setCharacterEncoding("utf-8");
		
		String method = req.getParameter("method");
		if("register".equals(method)) {
			String account = req.getParameter("account");
			String password = req.getParameter("password");
			String nickname = req.getParameter("nickname");
			
			SysUser u = new SysUser();
			u.setAccount(account);
			u.setPassword(password);
			u.setNickname(nickname);
			
			userService.add(u);
			
			req.getSession().setAttribute("user", u);
			resp.sendRedirect(req.getServletContext().getContextPath() + "/index.jsp");
		} else if("login".equals(method)) {
			String account = req.getParameter("account");
			String password = req.getParameter("password");
			
			SysUser user = userService.login(account, password);
			if(user != null) {
				System.out.println("登录成功");
				// 重定向
				req.getSession().setAttribute("user", user);
				resp.sendRedirect(req.getServletContext().getContextPath() + "/index.jsp");
			} else {
				System.out.println("账号或者密码错误");
			} 
			
		} else if("logout".equals(method)) {
			req.getSession().removeAttribute("user");
			resp.sendRedirect(req.getServletContext().getContextPath() + "/index.jsp");
		}
	}

}
